using UnityEngine;
using System.Collections;
using System.IO;
using System.Collections.Generic;
using UnityEditor;
using UnityEditorInternal;
using System;
using System.Text.RegularExpressions;
using Newtonsoft.Json;

public class AutoBuildAnim : AssetPostprocessor
{
	static string filePath = "Assets/TempData/raw_copy.json";
	static string localFilePath = "Assets/TempData/raw_local_copy.json";

	public static HashSet<string> getBuildCopyConfig(string resPath)
	{
		string buildAnimConfig = resPath + "/" + BuildAnimation.buildCopyName;
		
		TextAsset asset = AssetDatabase.LoadAssetAtPath(buildAnimConfig, typeof(TextAsset)) as TextAsset;
		if(asset == null)
		{
			return null;
		}
		HashSet<string> animPaths = JsonConvert.DeserializeObject<HashSet<string>>(asset.text);
		return animPaths;
	}

	[MenuItem("Custom/OldProject/Prefab/CreateNeedCopy")]
	static void createNeedAnim()
	{
		bool isAll = true;
		string[] resPaths = CreateSpriteSheet.bundleDir;
		string[] outputPaths = new string[]{filePath, localFilePath};
		for(int i = 0; i < resPaths.Length; i++)
		{
			string resPath = resPaths[i];
			string modifyFile = outputPaths[i];

			HashSet<string> hashSet = null;
			if(isAll)
			{
				hashSet = getBuildCopyConfig(resPath);
			}
			else
			{
				if(!File.Exists(modifyFile))
				{
					continue;
				}
				hashSet = JsonConvert.DeserializeObject<HashSet<string>>(File.ReadAllText(modifyFile));
			}




			MaterialTextureForETC1.BuildCopy2(resPath, hashSet);

			if(File.Exists(filePath))
			{
				CommonUtil.Move(modifyFile, CommonUtil.addSuffixToFileName(modifyFile, "_backup"));
            }

		}

		
		//		if(!File.Exists(filePath))
		//		{
		//			return;
		//		}
		//
		//		string str = CommonUtil.fileToString(filePath);
		//		HashSet<string> hashSet = JsonConvert.DeserializeObject<HashSet<string>>(str);
		
		
//		BuildAnimation.BuildAllAnimationsForSpriteSheet3(EditorCommonTool.build_target_ios, hashSet);
//		BuildAnimation.BuildAllAnimationsForSpriteSheet3(BuildTarget.Android, hashSet);
		
		//		BuildAnimation.SetAnimEvent();
		//		BuildAnimation.SetAnimEventForSpriteSheet();
		

		
		AssetDatabase.Refresh();
	}
	
	[MenuItem("Assets/Custom/OldProject/printAnimCurveType")]
	static void test_anim()
	{
		AnimationClip clip = Selection.activeObject as AnimationClip;
		EditorCurveBinding[] curveBindings = AnimationUtility.GetObjectReferenceCurveBindings (clip);
		for(int i = 0; i < curveBindings.Length; i++)
		{
			Debug.Log(curveBindings[i].propertyName + " " + curveBindings[i].type);
		}
	}
	
//	[MenuItem("Assets/Custom/OldProject/CreateAnimation")]
//	static void createAnim()
//	{
//		if(Selection.assetGUIDs == null || Selection.assetGUIDs.Length <= 0)
//		{
//			return;
//		}
//		
//		string p = AssetDatabase.GUIDToAssetPath(Selection.assetGUIDs[0]);
//		
//		string[] paths = Directory.GetFiles(p, "*.png", SearchOption.TopDirectoryOnly);
//		if(paths.Length > 1)
//		{
//			p = Path.GetDirectoryName(p);
//		}
//		
//		p = p.Replace(CreateSpriteSheet.bundleDir[0] + "/", "");
//		
//		bool found = false;
//		HashSet<string> config = EditorCommonTool.getBuildAnimConfig();
//		foreach(string path in config)
//		{
//			if(p.StartsWith(path))
//			{
//				found = true;
//				break;
//			}
//		}
//		
//		if(!found)
//		{
//			return;
//		}
//		
//		HashSet<string> hashSet = new HashSet<string>();
//		hashSet.Add(p);
//		
//		BuildAnimation.buildAllAnimations2(true, hashSet);
//		BuildAnimation.SetAnimEvent();
//		
//		AssetDatabase.SaveAssets();
//		AssetDatabase.Refresh();
//	}
	
	static void OnPostprocessAllAssets (
		string[] importedAssets,
		string[] deletedAssets,
		string[] movedAssets,
		string[] movedFromAssetPaths)
	{
		return;
		
		if(!File.Exists("/usr/local/bin/TexturePacker"))
		{
			return;
		}
		
		string[] resPaths = CreateSpriteSheet.bundleDir;
		string[] outputPaths = new string[]{filePath, localFilePath};
		for(int i = 0; i < resPaths.Length; i++)
		{
			string resPath = resPaths[i];
			HashSet<string> hashSet = getBuildCopyConfig(resPath);

			if(hashSet == null)
			{
				continue;
			}
			HashSet<string> newHashSet = new HashSet<string>();
			foreach(string p in hashSet)
			{
				newHashSet.Add(resPath + "/" + p);
			}
			getNeedUpdateAnimPath2(resPath, newHashSet, importedAssets, outputPaths[i]);
			getNeedUpdateAnimPath2(resPath, newHashSet, deletedAssets, outputPaths[i]);
			getNeedUpdateAnimPath2(resPath, newHashSet, movedAssets, outputPaths[i]);
			getNeedUpdateAnimPath2(resPath, newHashSet, movedFromAssetPaths, outputPaths[i]);
		}


		AssetDatabase.Refresh();

		//		HashSet<string> dirPaths = new HashSet<string>();
		//		if(File.Exists(filePath))
		//		{
		//			string str = CommonUtil.fileToString(filePath);
		//			dirPaths = JsonConvert.DeserializeObject<HashSet<string>>(str);
		//		}
		//
		//		HashSet<string> animDirs = EditorCommonTool.getBuildAnimConfig();
		//
		//		getNeedUpdateAnimPath(importedAssets, ref dirPaths, animDirs);
		//		getNeedUpdateAnimPath(deletedAssets, ref dirPaths, animDirs);
		//		getNeedUpdateAnimPath(movedAssets, ref dirPaths, animDirs);
		//		getNeedUpdateAnimPath(movedFromAssetPaths, ref dirPaths, animDirs);
		//
		//		if(dirPaths.Count > 0)
		//		{
		//			string content = JsonConvert.SerializeObject(dirPaths, Formatting.Indented);
		//			File.WriteAllText(filePath, content);
		//
		//			AssetDatabase.Refresh();
		//		}
	}
	
	static void getNeedUpdateAnimPath(string[] paths, ref HashSet<string> dirPaths, HashSet<string> animDirs)
	{
		if(paths == null)
		{
			return;
		}
		if(animDirs == null)
		{
			return;
		}
		string spritePath = CreateSpriteSheet.bundleDir[0] + "/";
		
		for(int i = 0; i < paths.Length; i++)
		{
			string path = paths[i];
			
			if(!path.StartsWith(spritePath))
			{
				continue;
			}
			
			string spritePath2 = path.Replace(spritePath, "");
			
			foreach(string dir in animDirs)
			{
				if(spritePath2.StartsWith(dir))
				{
					string ext = Path.GetExtension(spritePath2);
					string animDir = Path.GetDirectoryName(spritePath2);
					//					if(ext == null || ext == "")
					//					{
					//						animDir = path;
					//					}
					
					if(!dirPaths.Contains(animDir))
					{
						bool needAdd = true;
						HashSet<string> delDirs = new HashSet<string>();
						foreach(string dirPath in dirPaths)
						{
							if(dirPath.StartsWith(animDir))
							{
								delDirs.Add(dirPath);
							}
							else if(animDir.StartsWith(dirPath))
							{
								needAdd = false;
								break;
							}
						}
						
						if(needAdd)
						{
							dirPaths.Add(animDir);
						}
						
						foreach(string delDir in delDirs)
						{
							dirPaths.Remove(delDir);
						}
					}
					
					break;
				}
			}
		}
	}
	
	static void getNeedUpdateAnimPath2(string resPath, HashSet<string> hashSet, string[] paths, string outputFilePath)
	{
		string[] ext = new string[]{".anim", ".mat", ".prefab"};

		HashSet<string> set = null;
		if(File.Exists(outputFilePath))
		{
			string str = File.ReadAllText(outputFilePath);
			set = JsonConvert.DeserializeObject<HashSet<string>>(str);
		}
		else
		{
			set = new HashSet<string>();
		}

		bool needWrite = false;
		for(int i = 0; i < paths.Length; i++)
		{
			string path = paths[i];
			bool need = false;
			for(int j = 0; j < ext.Length; j++)
			{
				if(path.EndsWith(ext[j]))
				{
					need = true;
					break;
				}
			}

			if(!need)
			{
				continue;
			}

			foreach(string p in hashSet)
			{
				if(path.StartsWith(p))
				{
					needWrite = true;
					string outputStr = path.Remove(0, resPath.Length + 1);
					set.Add(outputStr);
				}
			}
		}

		if(needWrite)
		{
			string str2 = JsonConvert.SerializeObject(set, Formatting.Indented	);
			CommonUtil.stringToFile(outputFilePath, str2);
		}
	}
	
	//	static string filePath = "Assets/TempData/raw_anim.json";
	//
	//	[MenuItem("Custom/OldProject/Anim/CreateNeedAnim")]
	//	static void createNeedAnim()
	//	{
	//		HashSet<string> hashSet = EditorCommonTool.getBuildAnimConfig();
	//
	////		if(!File.Exists(filePath))
	////		{
	////			return;
	////		}
	////
	////		string str = CommonUtil.fileToString(filePath);
	////		HashSet<string> hashSet = JsonConvert.DeserializeObject<HashSet<string>>(str);
	//
	//
	//		BuildAnimation.BuildAllAnimationsForSpriteSheet3(EditorCommonTool.build_target_ios, hashSet);
	//		BuildAnimation.BuildAllAnimationsForSpriteSheet3(BuildTarget.Android, hashSet);
	//
	////		BuildAnimation.SetAnimEvent();
	////		BuildAnimation.SetAnimEventForSpriteSheet();
	//
	//		if(File.Exists(filePath))
	//		{
	//			File.Move(filePath, CommonUtil.addSuffixToFileName(filePath));
	//		}
	//
	//		AssetDatabase.Refresh();
	//	}
	//
	//	[MenuItem("Assets/Custom/OldProject/printAnimCurveType")]
	//	static void test_anim()
	//	{
	//		AnimationClip clip = Selection.activeObject as AnimationClip;
	//		EditorCurveBinding[] curveBindings = AnimationUtility.GetObjectReferenceCurveBindings (clip);
	//		for(int i = 0; i < curveBindings.Length; i++)
	//		{
	//			Debug.Log(curveBindings[i].propertyName + " " + curveBindings[i].type);
	//		}
	//	}
	//
	//	[MenuItem("Assets/Custom/OldProject/CreateAnimation")]
	//	static void createAnim()
	//	{
	//		if(Selection.assetGUIDs == null || Selection.assetGUIDs.Length <= 0)
	//		{
	//			return;
	//		}
	//
	//		string p = AssetDatabase.GUIDToAssetPath(Selection.assetGUIDs[0]);
	//
	//		string[] paths = Directory.GetFiles(p, "*.png", SearchOption.TopDirectoryOnly);
	//		if(paths.Length > 1)
	//		{
	//			p = Path.GetDirectoryName(p);
	//		}
	//
	//		p = p.Replace(CreateSpriteSheet.bundleDir[0] + "/", "");
	//
	//		bool found = false;
	//		HashSet<string> config = EditorCommonTool.getBuildAnimConfig();
	//		foreach(string path in config)
	//		{
	//			if(p.StartsWith(path))
	//			{
	//				found = true;
	//				break;
	//			}
	//		}
	//
	//		if(!found)
	//		{
	//			return;
	//		}
	//
	//		HashSet<string> hashSet = new HashSet<string>();
	//		hashSet.Add(p);
	//
	//		BuildAnimation.buildAllAnimations2(true, hashSet);
	//		BuildAnimation.SetAnimEvent();
	//
	//		AssetDatabase.SaveAssets();
	//		AssetDatabase.Refresh();
	//	}
	//	
	//	static void OnPostprocessAllAssets (
	//		string[] importedAssets,
	//		string[] deletedAssets,
	//		string[] movedAssets,
	//		string[] movedFromAssetPaths)
	//	{
	//		if(SwitchConfig.isBambooBuild)
	//		{
	//			return;
	//		}
	//
	//		if(!File.Exists("/usr/local/bin/TexturePacker"))
	//		{
	//			return;
	//		}
	//
	//		getNeedUpdateAnimPath2(importedAssets);
	//		getNeedUpdateAnimPath2(deletedAssets);
	//		getNeedUpdateAnimPath2(movedAssets);
	//		getNeedUpdateAnimPath2(movedFromAssetPaths);
	//
	////		HashSet<string> dirPaths = new HashSet<string>();
	////		if(File.Exists(filePath))
	////		{
	////			string str = CommonUtil.fileToString(filePath);
	////			dirPaths = JsonConvert.DeserializeObject<HashSet<string>>(str);
	////		}
	////
	////		HashSet<string> animDirs = EditorCommonTool.getBuildAnimConfig();
	////
	////		getNeedUpdateAnimPath(importedAssets, ref dirPaths, animDirs);
	////		getNeedUpdateAnimPath(deletedAssets, ref dirPaths, animDirs);
	////		getNeedUpdateAnimPath(movedAssets, ref dirPaths, animDirs);
	////		getNeedUpdateAnimPath(movedFromAssetPaths, ref dirPaths, animDirs);
	////
	////		if(dirPaths.Count > 0)
	////		{
	////			string content = JsonConvert.SerializeObject(dirPaths, Formatting.Indented);
	////			File.WriteAllText(filePath, content);
	////
	////			AssetDatabase.Refresh();
	////		}
	//	}
	//	
	//	static void getNeedUpdateAnimPath(string[] paths, ref HashSet<string> dirPaths, HashSet<string> animDirs)
	//	{
	//		if(paths == null)
	//		{
	//			return;
	//		}
	//		if(animDirs == null)
	//		{
	//			return;
	//		}
	//		string spritePath = CreateSpriteSheet.bundleDir[0] + "/";
	//
	//		for(int i = 0; i < paths.Length; i++)
	//		{
	//			string path = paths[i];
	//
	//			if(!path.StartsWith(spritePath))
	//			{
	//				continue;
	//			}
	//			
	//			string spritePath2 = path.Replace(spritePath, "");
	//
	//			foreach(string dir in animDirs)
	//			{
	//				if(spritePath2.StartsWith(dir))
	//				{
	//					string ext = Path.GetExtension(spritePath2);
	//					string animDir = Path.GetDirectoryName(spritePath2);
	////					if(ext == null || ext == "")
	////					{
	////						animDir = path;
	////					}
	//
	//					if(!dirPaths.Contains(animDir))
	//					{
	//						bool needAdd = true;
	//						HashSet<string> delDirs = new HashSet<string>();
	//						foreach(string dirPath in dirPaths)
	//						{
	//							if(dirPath.StartsWith(animDir))
	//							{
	//								delDirs.Add(dirPath);
	//							}
	//							else if(animDir.StartsWith(dirPath))
	//							{
	//								needAdd = false;
	//								break;
	//							}
	//						}
	//
	//						if(needAdd)
	//						{
	//							dirPaths.Add(animDir);
	//						}
	//
	//						foreach(string delDir in delDirs)
	//						{
	//							dirPaths.Remove(delDir);
	//						}
	//					}
	//
	//					break;
	//				}
	//			}
	//		}
	//	}
	//
	//	static void getNeedUpdateAnimPath2(string[] paths)
	//	{
	//		if(File.Exists(filePath))
	//		{
	//			return;
	//		}
	//		string spritePath = CreateSpriteSheet.bundleDir[0] + "/" + ResourcesEx.AnimDirName;
	//		for(int i = 0; i < paths.Length; i++)
	//		{
	//			if(paths[i].Contains(spritePath))
	//			{
	//				File.WriteAllText(filePath, "");
	//				AssetDatabase.Refresh();
	//				return;
	//			}
	//		}
	//	}
}
